//
//  RootViewController.m
//  MGSplitView
//
//  Created by Matt Gemmell on 26/07/2010.
//  Copyright Instinctive Code 2010.
//

#import "MGTreeViewController.h"


#import "GBall.h"
#import "SourceListItem.h"
#import "PXTableObject.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBTableColumnHeader_key.h"


@implementation MGTreeViewController

@synthesize cods_array;
@synthesize chartViewController,quoteViewController,delgete_AppDelegate;
@synthesize datasourceManager, sortDescriptors,datamodel_chart;



#pragma mark -
#pragma mark 載入畫面
 
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    //工具列
    {
        //樹狀工具列 初始化
        toolbar_tree = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 1024, 44)]; 
        
        //各按鈕
        {
            //編輯
            Item_edit_folderORwatchlist = [[UIBarButtonItem alloc] initWithTitle:@"編輯" style:UIBarButtonItemStyleBordered target:self action:@selector(toggle_tree_edit_folderORwatchlist:)];            
            
            
            //更名
            Item_rename_folderORwatchlist=  [[UIBarButtonItem alloc] initWithTitle:@"更名" style:UIBarButtonItemStyleBordered target:self action:@selector(toggle_tree_rename_folderORwatchlist:)]; 
            
            
            //複製
            Item_copy_folderORwatchlist=  [[UIBarButtonItem alloc] initWithTitle:@"複製" style:UIBarButtonItemStyleBordered target:self action:@selector(toggle_tree_copy_folderORwatchlist:)];             
            
            //排序
            Item_sort_folderORwatchlist=  [[UIBarButtonItem alloc] initWithTitle:@"排序" style:UIBarButtonItemStyleBordered target:self action:@selector(toggle_tree_sort_folderORwatchlist:)];             
            
            //彈性空間
            Item_fix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                     target:nil 
                                                                     action:nil ];        
            
            //新增
            Item_add_folderORwatchlist  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                                        target:self 
                                                                                        action:@selector(toggle_tree_add_folderORwatchlist:)];         
            
        
        }
                
        //加入到toolbar
        [toolbar_tree setItems:[NSArray arrayWithObjects:Item_edit_folderORwatchlist,Item_rename_folderORwatchlist,Item_copy_folderORwatchlist,Item_sort_folderORwatchlist ,Item_fix,Item_add_folderORwatchlist ,nil] animated:YES];      
        
        //消滅
        [Item_add_folderORwatchlist release];   
        [Item_fix release];
        [Item_edit_folderORwatchlist release];
        [Item_rename_folderORwatchlist release];
        [Item_sort_folderORwatchlist release];        
        [Item_copy_folderORwatchlist release];
        
        
    }
    
    //表格
    {
        treetable =[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 1024, 44) style:UITableViewStylePlain];
        treetable.dataSource = self;	
        treetable.delegate=self;    
    }
    
    //表格資料管理
    {
        sortDescriptors   = [tree_DatasourceManager defaultSortDescriptors];    
        
        datasourceManager = [[tree_DatasourceManager alloc] initWithRootPath:[self applicationDocumentsDirectory] sortDescriptors:sortDescriptors datamodel:datamodel_chart];
        datasourceManager.delegate = self;
    }
     
    //view 視圖加入
    {
        //工具列
        [self.view addSubview:toolbar_tree];
       
        //表格
        [self.view addSubview:treetable];   
    }
      
}

- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

#pragma mark -
#pragma mark 底層框架改變

-(void)view_frame_size_change:(CGRect)newframe{
    
    NSLog(@"view_frame_size_change w=%f h=%f",newframe.size.width,newframe.size.height);     
    
    CGRect tableframe;
    tableframe.size.width=newframe.size.width;
    tableframe.size.height=newframe.size.height-44;
    tableframe.origin.x=0; //因為是在自身的view加入 原點設定為(0,0)
    tableframe.origin.y=0+ 44;
    
    treetable.frame =tableframe;
    
    CGRect toolbarframe;
    toolbarframe.size.width=newframe.size.width;
    toolbarframe.size.height= 44;
    toolbarframe.origin.x=0;//因為是在自身的view加入 原點設定為(0,0)
    toolbarframe.origin.y=0;
    
    toolbar_tree.frame=toolbarframe;
    
    
}


-(void)tableview_reload:(NSMutableArray *)cods_a{
 
    if (cods_array !=cods_a) {
        [cods_array release];
        
        cods_array=[cods_a retain];
        [treetable reloadData];  
        
    }
   
    
}

// Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}
 
- (void)selectFirstRow
{
	if ([treetable numberOfSections] > 0 && [treetable numberOfRowsInSection:0] > 0) {
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
		[treetable selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
		[self tableView:treetable didSelectRowAtIndexPath:indexPath];
	}
}


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"didSelectRowAtIndexPath");
    
	treeNode *file = [datasourceManager.mergedRootBranch objectAtIndex:indexPath.row];
	
    if (file.isDirectory) {
		NSLog(@"是資料夾");
        if (file.isExpanded){
			NSLog(@"目前是打開");
           
            tree_ViewCell *curCell = (tree_ViewCell *)[aTableView cellForRowAtIndexPath:indexPath];
            
            curCell.expanded = NO; //讓三角形旋轉的關鍵
			
            [datasourceManager collapseBranchAtIndex:indexPath.row]; //資料夾下面的目錄顯示出來關鍵
            
            file.expanded = NO;
            
		}
		else{
            NSLog(@"目前是關閉");
            
			tree_ViewCell *curCell = (tree_ViewCell *)[aTableView cellForRowAtIndexPath:indexPath];
			
            curCell.expanded = YES; //讓三角形旋轉的關鍵
			
            [datasourceManager expandBranchAtIndex:indexPath.row];
            file.expanded = YES;
            
                        
            
            
		}
		
		//[self.tableView reloadData]; //do not update datasource or tableview here		
		//rows will be inserted/deleted using datasourceManager delegate methods
		
	}
	else{
      
        
	}
    //更新組合與 回補報價資料
    {
        
         
        SourceListItem *si= [file self_path_SourceListItem] ;
        //重要：針對此節點下 重新彙整所有下面階層的組合數據
        [datamodel_chart tree_folder_tableobject_refresh:si];
        
        NSLog(@"更新組合與 回補報價資料=%@ title=%@",[file self_path_SourceListItem ],[si title]);        
        
        NSMutableArray *code_array= [[NSMutableArray alloc] init]  ;         
              
         
        NSLog(@"報價回補的數目=%i",  [[[si tableobject] data_array_object] count]   );
       
        if ([[[si tableobject] data_array_object] count]==0) {
            //如果結點上沒有股票 就更新一次
            [datamodel_chart update_all_tree_folder_tableobject_refresh:1];
        }
                 
        for (Data_Object *cc in  [[si tableobject] data_array_object])  {
          
             NSLog(@"code=%@",[[cc table_data] objectForKey:DB_object_sqlite_basic_code]);  
            
            [code_array addObject:[[cc table_data] objectForKey:DB_object_sqlite_basic_code]];
            
            
        }
        
        //更新股票組合
        self.cods_array=code_array; 
        
        index_chart=0;   
       
        if ( [code_array count]> 0) {
            //有股票數量超過0才可以回補
            [datamodel_chart Quote_Start:code_array];             
        }
        
       
        
        [code_array release];
    }        
        
}

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{
	treeNode *file = [datasourceManager.mergedRootBranch objectAtIndex:indexPath.row];
	return file.level; 
}

#pragma mark -
#pragma mark Table view delegate 編輯
//編輯狀態 哪些列可以進行編輯
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (indexPath.row!=0) {
        //treeNode *file = [datasourceManager.mergedRootBranch objectAtIndex:indexPath.row];    
        
        //NSLog(@"編輯狀態 %@= %@",[file name], [file self_path_SourceListItem]);
        
        
        return UITableViewCellEditingStyleDelete;
    }
    else {
         //return UITableViewCellEditingStyleNone;
        
         return UITableViewCellEditingStyleDelete;    }
    
    
  
} 
#pragma mark -
#pragma mark Table view delegate 排列

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row!=0) {
         return YES;
    }
    else {
        // return NO;
         return YES;
    }
  
   
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
   
    if (destinationIndexPath.row==0) {    
        //[treetable reloadData];
          [datasourceManager treeNodemoveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];        
    }    
    else {
        [datasourceManager treeNodemoveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
        
    }
   
}


- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
	
         treeNode *file = [datasourceManager.mergedRootBranch objectAtIndex:indexPath.row];         
         NSLog(@"刪除列=%i %@",indexPath.row, [file name] );        
         		
		[datasourceManager deleteFileAtIndex:indexPath.row];
        [treetable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
		 
    }   
     
}



#pragma mark -
#pragma mark 表格資料處理

- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"numberOfRowsInSection=%i",[datasourceManager.mergedRootBranch count] );
	return [datasourceManager.mergedRootBranch count];
}


- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"MyCellIdentifier";
	tree_ViewCell *cell = (tree_ViewCell *)[aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
		cell = [[[tree_ViewCell alloc] initWithReuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
		cell.indentationWidth = 30.0;
        
    }
    
	treeNode *file = [datasourceManager.mergedRootBranch objectAtIndex:indexPath.row];
	
    cell.cellType = (file.isDirectory)? N4TableViewCellTypeDirectory : N4TableViewCellTypeFile;
	cell.directoryAccessoryImageView.image = (file.isDirectory)? [UIImage imageNamed:@"TriangleSmall.png"] : nil;
	cell.imageView.image = [file image];
	
    cell.textLabel.text = [file name]; 
	cell.detailTextLabel.text = [[file parentkey]  name];
    
   // int count_child=[[[file self_path_SourceListItem] children] count];
    int count_stock=[[[[file self_path_SourceListItem] tableobject] data_array_onlyfortableObject] count];
    
    [cell drawbage: [NSString stringWithFormat:@"%i",count_stock]  ]; 
    
	return cell;
}
 
 
#pragma mark - 
#pragma mark tree_DatasourceManagerDelegate methods

- (void) fileAccordionDatasourceManager_tree_reload{
  
    [treetable reloadData];

}
 

- (void) fileAccordionDatasourceManager:(tree_DatasourceManager *) manager didSelecrRowsAtIndexPaths:(NSArray *)indexPaths{
    
    NSLog(@"didSelecrRowsAtIndexPaths=%@",  [indexPaths objectAtIndex:0] );
   
    [treetable selectRowAtIndexPath: [indexPaths objectAtIndex:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    
    [self tableView:treetable didSelectRowAtIndexPath: [indexPaths objectAtIndex:0]]; 
    
    /*
    
    if ([indexPaths count] == 1) { //ok here? 此段程式的意義？
        [treetable selectRowAtIndexPath:[indexPaths objectAtIndex:0] 
                               animated:YES scrollPosition:UITableViewScrollPositionBottom];
	}
    */
    
}

- (void) fileAccordionDatasourceManager:(tree_DatasourceManager *) manager didInsertRowsAtIndexPaths:(NSArray *)indexPaths{
    NSLog(@"ffffg");
    
    
	[treetable insertRowsAtIndexPaths:indexPaths 
						  withRowAnimation: UITableViewRowAnimationLeft];
	
    if ([indexPaths count] == 1) { //ok here? 此段程式的意義？
        [treetable selectRowAtIndexPath:[indexPaths objectAtIndex:0] 
                                    animated:YES scrollPosition:UITableViewScrollPositionNone];
	}
    
}
- (void) fileAccordionDatasourceManager:(tree_DatasourceManager *) manager didRemoveRowsAtIndexPaths:(NSArray *)indexPaths{
	
    [treetable deleteRowsAtIndexPaths:indexPaths 
						  withRowAnimation:UITableViewRowAnimationLeft];
}

- (void) fileAccordionDatasourceManager:(tree_DatasourceManager *) manager didCreateSuccessfullyFile:(treeNode *) file{
	
}
- (void) fileAccordionDatasourceManager:(tree_DatasourceManager *) manager didFailOnCreationofFile:(treeNode *)file error:(NSError *)error{
	
}




#pragma mark -
#pragma mark Memory management


- (void)dealloc
{
      
    [cods_array release];    
    
    [chartViewController release];
    [super dealloc];
}
#pragma mark -
#pragma mark 更新報價
-(void)start_quote_table_refresh{
    NSLog(@"start_quote_table_refresh=%@",cods_array);
    //更新報價
    [quoteViewController tableview_reload:cods_array];
    
    //指定第一個走勢圖更新
    //[quoteViewController selectFirstRow];
    
    
    [quoteViewController selectRow: index_chart  ]  ;   
    index_chart= index_chart +1;  
    
}

//測試使用
-(void)drawnext_index{
    
    NSLog(@"drawnext_index=%i", index_chart);
   
    if ([self.cods_array count]> index_chart  ) {
        
        [quoteViewController selectRow: index_chart  ];   
          index_chart= index_chart +1;   
    }
   
    
}

#pragma mark -
#pragma mark 工具列執行方法
//進入排列狀態
- (void)toggle_tree_arrange_folderORwatchlist:(id)sender{
    NSLog(@"排列");	
     
    //先合併打開的
     /*    
    for (int i=[datasourceManager.mergedRootBranch count]-1  ; i>=0; i--) {
        treeNode *tt=[datasourceManager.mergedRootBranch objectAtIndex:i];
        NSLog(@"tt=%@",[tt name] );
        
        if (tt.isDirectory==YES && tt.expanded==YES) {
           
            [datasourceManager collapseBranchAtIndex:i];
             
        }
        
        
    }
    */
    
    
    [treetable setEditing:YES animated:YES];
}

//增加
- (void)toggle_tree_add_folderORwatchlist:(id)sender{
	
	if (!fileCreatorPopoverController.popoverVisible) {
		
		//[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
		
		int w = 240, h = 44;
		UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, h*4)];
		
        //增加群組 相同階層
        UIButton *button_add_folder_level_same = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, w, h)];
		[button_add_folder_level_same addTarget:self action:@selector(sel_createDirectoryAlert_level_same) forControlEvents:UIControlEventTouchUpInside];
		[button_add_folder_level_same setTitle:@"同一階層 新增群組" forState:UIControlStateNormal];
		[container addSubview:button_add_folder_level_same];
		[button_add_folder_level_same release];
		
        //增加群組 下一個階層
        UIButton *button_add_folder_level_sub = [[UIButton alloc] initWithFrame:CGRectMake(0, 44, w, h)];
		[button_add_folder_level_sub addTarget:self action:@selector(sel_createDirectoryAlert_level_sub) forControlEvents:UIControlEventTouchUpInside];
		[button_add_folder_level_sub setTitle:@"下一階層 新增群組" forState:UIControlStateNormal];
		[container addSubview:button_add_folder_level_sub];
        [button_add_folder_level_sub release];
        
        
        //增加自選股組合 相同階層
		UIButton *_add_watchlist_level_same  = [[UIButton alloc] initWithFrame:CGRectMake(0, 88, w, h)];
		[_add_watchlist_level_same addTarget:self action:@selector(sel_createwatchlistAlert_level_same) forControlEvents:UIControlEventTouchUpInside];
		[_add_watchlist_level_same setTitle:@"同一階層 新增自選股" forState:UIControlStateNormal];
		[container addSubview:_add_watchlist_level_same];
		[_add_watchlist_level_same release];
		
        //增加自選股組合 下一個階層
		UIButton *_add_watchlist_level_sub  = [[UIButton alloc] initWithFrame:CGRectMake(0, 132, w, h)];
		[_add_watchlist_level_sub addTarget:self action:@selector(sel_createwatchlistAlert_level_sub) forControlEvents:UIControlEventTouchUpInside];
		[_add_watchlist_level_sub setTitle:@"下一階層 新增自選股" forState:UIControlStateNormal];
		[container addSubview:_add_watchlist_level_sub];
		[_add_watchlist_level_sub release];
        
        
        /*
		UIButton *button3 = [[UIButton alloc] initWithFrame:CGRectMake(0, 132, w, h)];
		[button3 addTarget:self action:@selector(duplicateFileAlert) forControlEvents:UIControlEventTouchUpInside];
		[button3 setTitle:@"Duplicate File ... " forState:UIControlStateNormal];
		[container addSubview:button3];
		NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
		if (!selectedIndexPath ||
			((treeNode *)[datasourceManager.mergedRootBranch objectAtIndex:selectedIndexPath.row]).isDirectory) [button3 setEnabled:NO];
		[button3 release];
		*/
        
		UIViewController *vc = [[UIViewController alloc] init];
		vc.view = container;
		[container release];
		
		fileCreatorPopoverController = [[UIPopoverController alloc] initWithContentViewController:vc];
		[vc release];
		
		
		[fileCreatorPopoverController setPopoverContentSize:CGSizeMake(w, h*4)];
		[fileCreatorPopoverController presentPopoverFromBarButtonItem:sender 
                                             permittedArrowDirections:UIPopoverArrowDirectionAny
                                                             animated:YES];
		[fileCreatorPopoverController setDelegate:self];
	}
    
}
//進入編輯狀態
- (void)toggle_tree_edit_folderORwatchlist:(id)sender{
    NSLog(@"編輯列");	
   
     
    
    
   // [Item_edit_folderORwatchlist setTitle:@"完成"];
    //[Item_edit_folderORwatchlist setStyle:UIBarButtonSystemItemAdd];
    //加入到toolbar
    //新增
    
    Item_edit_folderORwatchlist  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                                                                target:self 
                                                                                action:@selector(toggle_tree_edit_done_folderORwatchlist:)];     
    
    
    
     [toolbar_tree setItems:[NSArray arrayWithObjects:Item_edit_folderORwatchlist,Item_rename_folderORwatchlist,Item_copy_folderORwatchlist,Item_sort_folderORwatchlist ,Item_fix,Item_add_folderORwatchlist ,nil] animated:YES];        
    
    [Item_edit_folderORwatchlist release];
    
    
    [treetable setEditing:YES];
}
//尚未進入編輯狀態
- (void)toggle_tree_edit_done_folderORwatchlist:(id)sender{
    NSLog(@"編輯列");	
    
    
    
    
    // [Item_edit_folderORwatchlist setTitle:@"完成"];
    //[Item_edit_folderORwatchlist setStyle:UIBarButtonSystemItemAdd];
    //加入到toolbar
    //新增
    
    Item_edit_folderORwatchlist = [[UIBarButtonItem alloc] initWithTitle:@"編輯" style:UIBarButtonItemStyleBordered target:self action:@selector(toggle_tree_edit_folderORwatchlist:)];      
    
    
     [toolbar_tree setItems:[NSArray arrayWithObjects:Item_edit_folderORwatchlist,Item_rename_folderORwatchlist,Item_copy_folderORwatchlist,Item_sort_folderORwatchlist ,Item_fix,Item_add_folderORwatchlist ,nil] animated:YES];   
    
     [Item_edit_folderORwatchlist release];   
    
     [treetable setEditing:NO];   
    
    
   //	NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    //[treetable selectRowAtIndexPath: indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    //8[treetable selectRowAtIndexPath: indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    
    //切記：只可以點選一次，如果連續點及兩次以上 會容易造成當機 
    //[self tableView:treetable didSelectRowAtIndexPath:indexPath]; 
      
}

- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController{
	return YES;
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController{
    
    if (popoverController == fileCreatorPopoverController) {
		[fileCreatorPopoverController release];
		fileCreatorPopoverController = nil;
	}
    
}
#pragma mark -
#pragma mark 樹狀節點增加 執行事件 排序

- (void)toggle_tree_sort_folderORwatchlist:(id)sender{
    NSLog(@"toggle_tree_sort_folderORwatchlist");
    
    
}



#pragma mark -
#pragma mark 樹狀節點增加 執行事件 複製

- (void)toggle_tree_copy_folderORwatchlist:(id)sender{
    NSLog(@"toggle_tree_copy_folderORwatchlist");
    
    NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSInteger selectedIndex = (!selectedIndexPath) ? -1 : selectedIndexPath.row;
	
    if (selectedIndex>=0) {
        
       
        
        
        [datasourceManager copy_AtIndex: selectedIndex  ]; 
        
        //[ActivityIndicator  stopAnimating];           
    }
    
    
    
}

#pragma mark -
#pragma mark 樹狀節點增加 執行事件 更名

- (void)toggle_tree_rename_folderORwatchlist:(id)sender{
    
    [self alter_Show_rename];
    
}



//修改名稱視窗顯示

-(void)alter_Show_rename{
    NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSString *message;
	    
    if (!selectedIndexPath){
		message = @"必須選定一個列，當作增加群組的起始點位置";
        
        UIAlertView *error=[[UIAlertView alloc] initWithTitle:@"警告!" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定",nil];
        [error show];
        [error release];
        
    }
    
    else{
        rename_prompt = [AlertPrompt alloc];
        
        rename_prompt = [rename_prompt initWithTitle:@"更改名稱" message:@"<輸入新名稱>" delegate:self cancelButtonTitle:@"取消" okButtonTitle:@"確定"];
        
        //下面這段會將顯示的改名稱視窗往下面移動 美觀考量
        rename_prompt.transform = CGAffineTransformTranslate( rename_prompt.transform, 0.0, - 100.0 );    
        
        [rename_prompt show];
        [rename_prompt release];  
        
        
        
	}
    
   
    
    
    
    
}
#pragma mark -
#pragma mark 樹狀節點增加 執行事件
//執行是否視窗 增加節點 在同一階層
- (void)sel_createDirectoryAlert_level_same {
	NSLog(@"createDirectoryAlert_level_same");
	
	NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSString *message;
	if (!selectedIndexPath)
		message = @"必須選定一個列，當作增加群組的起始點位置";
	
    
    else{
        message =@"完成";
		 
            
       
	}
  
    createDirectoryAlert_level_same = [[UIAlertView alloc] initWithTitle:@"sel_createDirectoryAlert_level_same" 
                                                                 message:message
                                                                delegate:self 
                                                       cancelButtonTitle:@"Cancel" 
                                                       otherButtonTitles:@"OK", nil];
    [createDirectoryAlert_level_same show];
    [createDirectoryAlert_level_same release];	   	
}
//執行是否視窗 增加節點 在同一階層
- (void)sel_createDirectoryAlert_level_sub{
	NSLog(@"createDirectoryAlert_level_sub");
	
	NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSString *message;
	if (!selectedIndexPath)
		message = @"必須選定一個列，當作增加群組的起始點位置";
	else{
        message =@"完成";
        
        
        
        /*
         if (file.isDirectory) 
         message = [NSString stringWithFormat:@"New directory will be created inside of %@", [file name]];
         else
         message = [NSString stringWithFormat:@"New directory will be created at same level of %@", [file name]];
         */
	}
    
	createDirectoryAlert_level_sub = [[UIAlertView alloc] initWithTitle:@"sel_createDirectoryAlert_level_sub" 
                                                                 message:message
                                                                delegate:self 
                                                       cancelButtonTitle:@"Cancel" 
                                                       otherButtonTitles:@"OK", nil];
	[createDirectoryAlert_level_sub show];
	[createDirectoryAlert_level_sub release];	 
}
- (void)sel_createwatchlistAlert_level_same{
	NSLog(@"createwatchlistAlert_level_same");
	
	NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSString *message;
	if (!selectedIndexPath)
		message = @"必須選定一個列，當作增加群組的起始點位置";
	else{
        message =@"完成";
        
        
        
        /*
         if (file.isDirectory) 
         message = [NSString stringWithFormat:@"New directory will be created inside of %@", [file name]];
         else
         message = [NSString stringWithFormat:@"New directory will be created at same level of %@", [file name]];
         */
	}
    
	createwatchlistAlert_level_same = [[UIAlertView alloc] initWithTitle:@"sel_createwatchlistAlert_level_same" 
                                                                 message:message
                                                                delegate:self 
                                                       cancelButtonTitle:@"Cancel" 
                                                       otherButtonTitles:@"OK", nil];
	[createwatchlistAlert_level_same show];
	[createwatchlistAlert_level_same release];	     
    
     
}
- (void)sel_createwatchlistAlert_level_sub{
	NSLog(@"createwatchlistAlert_level_sub");
	
	NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSString *message;
	if (!selectedIndexPath)
		message = @"必須選定一個列，當作增加群組的起始點位置";
	else{
        message =@"完成";
        
        
        
        /*
         if (file.isDirectory) 
         message = [NSString stringWithFormat:@"New directory will be created inside of %@", [file name]];
         else
         message = [NSString stringWithFormat:@"New directory will be created at same level of %@", [file name]];
         */
	}
    
	createwatchlistAlert_level_sub = [[UIAlertView alloc] initWithTitle:@"sel_createwatchlistAlert_level_sub" 
                                                                 message:message
                                                                delegate:self 
                                                       cancelButtonTitle:@"Cancel" 
                                                       otherButtonTitles:@"OK", nil];
	[createwatchlistAlert_level_sub show];
	[createwatchlistAlert_level_sub release];	     
    
    
}

- (void) duplicateFileAlert{
	 
}


- (void) createFile{
	 
    
}
- (void) duplicateFile{
	 
    
}

- (void) willPresentAlertView:(UIAlertView *)alertView{
    [fileCreatorPopoverController dismissPopoverAnimated:YES];
	[fileCreatorPopoverController release];
	fileCreatorPopoverController = nil;	
}

#pragma mark -
#pragma mark UIAlertView 視窗 事件
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)index{
	 
    if (index != 0) {
		
        if (alertView == createwatchlistAlert_level_same)      [self createwatchlist_level_same];
		else if (alertView == createwatchlistAlert_level_sub)  [self createwatchlist_level_sub];        
        else if (alertView == createDirectoryAlert_level_same) [self createDirectory_same_level];
        else if (alertView == createDirectoryAlert_level_sub)  [self createDirectory_same_sub];        
		else if (alertView == duplicateFileAlert) [self duplicateFile];
        else if ((AlertPrompt *)alertView == rename_prompt) {
            
            NSString *entered_name = [(AlertPrompt *)alertView enteredText];
        
            if ([entered_name isEqualToString:@""] ) {
                //如果輸入的是空白 在重新一次
                [self alter_Show_rename];
                  
            }
            else {
                NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
                
                NSInteger selectedIndex = (!selectedIndexPath) ? -1 : selectedIndexPath.row;    
                
               [datasourceManager rename_AtIndex:selectedIndex newname:entered_name];
            }
            
                       
            
            
        }
   
         
	}
     
    
}
- (void) alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
  
    NSLog(@"willDismissWithButtonIndex=%i ",buttonIndex  );    
   
        
    
    //[((UIAlertView *)alertView).textField resignFirstResponder];
    //[((UIAlertView *)alertView).textField removeFromSuperview];  
    //[((UIAlertView *)alertView).textField release];  
}



#pragma mark -
#pragma mark 樹狀節點增加 執行事件 增加
- (void) createDirectory_same_level{
	NSLog(@"createDirectory_same_level"); 
    
    NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSInteger selectedIndex = (!selectedIndexPath) ? -1 : selectedIndexPath.row;
	
    if (selectedIndex>=0) {
        [treetable deselectRowAtIndexPath:[treetable indexPathForSelectedRow] animated:YES];
        
        [datasourceManager createDirectoryAtIndex_level_same:selectedIndex withName:[NSString stringWithFormat:@"Directory%i", (arc4random()%1000)]]; 
    }
    
  
    
	
}
- (void) createDirectory_same_sub{
	NSLog(@"createDirectory_same_sub"); 
    
    NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSInteger selectedIndex = (!selectedIndexPath) ? -1 : selectedIndexPath.row;
	
    if (selectedIndex>=0) {
        [treetable deselectRowAtIndexPath:[treetable indexPathForSelectedRow] animated:YES];
        
        [datasourceManager createDirectoryAtIndex_level_sub:selectedIndex withName:[NSString stringWithFormat:@"Directory%i", (arc4random()%1000)]]; 
    }
    
    
    
	
}
- (void) createwatchlist_level_same{
	NSLog(@"createwatchlist_level_same"); 
    NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSInteger selectedIndex = (!selectedIndexPath) ? -1 : selectedIndexPath.row;
	
    if (selectedIndex>=0) {
        [treetable deselectRowAtIndexPath:[treetable indexPathForSelectedRow] animated:YES];
        
        [datasourceManager createWatchlistAtIndex_level_same:selectedIndex withName:[NSString stringWithFormat:@"Directory%i", (arc4random()%1000)]];            
    }
   
    
	
}
- (void) createwatchlist_level_sub{
	NSLog(@"createwatchlist_level_sub"); 
    
    NSIndexPath *selectedIndexPath = [treetable indexPathForSelectedRow];
	
    NSInteger selectedIndex = (!selectedIndexPath) ? -1 : selectedIndexPath.row;
	
    if (selectedIndex>=0) {
        [treetable deselectRowAtIndexPath:[treetable indexPathForSelectedRow] animated:YES];
        
        [datasourceManager createWatchlistAtIndex_level_sub:selectedIndex withName:[NSString stringWithFormat:@"Directory%i", (arc4random()%1000)]];    
    }    
    
	
}

@end
